using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace IppServer.Host.Configuration
{
    internal static class AppSettingsStore
    {
        private const string FileName = "appsettings.json";
        private const string CompanyFolderName = "IppServer";

        private static readonly DataContractJsonSerializer Serializer =
            new(typeof(AppSettings), new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true });

        public static AppSettings Load()
        {
            var path = GetPath();

            if (!File.Exists(path))
            {
                return AppSettings.CreateDefault();
            }

            try
            {
                using (var stream = File.OpenRead(path))
                {
                    return (AppSettings)Serializer.ReadObject(stream);
                }
            }
            catch (Exception)
            {
                return AppSettings.CreateDefault();
            }
        }

        public static void Save(AppSettings settings)
        {
            var path = GetPath();
            Directory.CreateDirectory(Path.GetDirectoryName(path) ?? AppDomain.CurrentDomain.BaseDirectory);

            using (var stream = new MemoryStream())
            {
                using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, ownsStream: false, indent: true))
                {
                    Serializer.WriteObject(writer, settings);
                    writer.Flush();
                }
                var json = Encoding.UTF8.GetString(stream.ToArray());
                File.WriteAllText(path, json);
            }
        }

        /// <summary>
        /// 获取配置文件完整路径（面向单位/服务器版本）：
        /// 使用公共应用数据目录：%ProgramData%\IppServer\appsettings.json
        /// </summary>
        public static string GetPath()
        {
            var baseDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            var appDir = Path.Combine(baseDir, CompanyFolderName);
            return Path.Combine(appDir, FileName);
        }
    }
}

